<?php

namespace App\Exceptions;

use App\Libs\Code\ErrorCode;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Response;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param \Exception $exception
     *
     * @return void
     */
    public function report( Exception $exception )
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Exception               $exception
     *
     * @return \Illuminate\Http\Response
     */
    public function render( $request, Exception $exception )
    {
        if ( config('app.debug') ) {
            $error      = $this->convertExceptionToResponse($exception);
            $statusCode = $error->getStatusCode();
            if ( ! $message = $exception->getMessage() ) $message = sprintf('%d %s', $statusCode, Response::$statusTexts[ $statusCode ]);
            $replacements = [
                'line'  => $exception->getLine(),
                'file'  => $exception->getFile(),
                'class' => get_class($exception),
                'trace' => explode("\n", $exception->getTraceAsString()),
            ];
            if ( $request->ajax() ) return data($replacements, $message, $statusCode);
            else return parent::render($request, $exception);
        }
        if ( $request->ajax() ) return message(( new ErrorCode() )::message(1000), 500);
        else return parent::render($request, $exception);
    }
}
